<script setup>
import { reactive, ref } from 'vue'
import { postFileApi } from "@/api/file"
import FeedbackList from '@/components/feedbackList.vue'
import {useUserStore} from '@/stores/user.js'
import {getUserFeedBackApi,delFeedBackApi,addFeedBackApi,updateFeedBackApi} from '@/api/feedback'
//获取用户信息
const userStore = useUserStore()
const userInfo = userStore.userInfo
import upImg from "@/components/upImg.vue";
import { feedbackStatus } from '@/utils/globleVar'
import {useRouter} from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus';
const router = useRouter()
const feedbackList = reactive({
    feedbacks:[]
})
const showFeedbackList = reactive({
    feedbacks:[],
    pageInfo:{}
})
//获取登录用户的所有反馈
getFeedbackList(0,userInfo.id)
async function getFeedbackList(page,userId){
   try{
      const resp = await getUserFeedBackApi(page,userId)
      if(resp.data.code === 200){
        if(page === 0){
            showFeedbackList.feedbacks = []
        }
        showFeedbackList.pageInfo = resp.data.data.page
        feedbackList.feedbacks = resp.data.data.content
        feedbackList.feedbacks.forEach(feedback =>{
           showFeedbackList.feedbacks.push(feedback)
        })
      } 
   }catch(e){
      console.log(e)
   }
}
//删除反馈
const clickDel = async (feedbackId)=>{
   ElMessageBox.confirm(
        '确认删除？',
        '温馨提示',
        {
          confirmButtonText:'删除',
          cancelButtonText:'取消',
          type:'warning'
        }
      ).then( async()=>{
        try{
        const resp = await delFeedBackApi(feedbackId)
        if(resp.data.code == 200 ){
            getFeedbackList(0,userInfo.id)
            ElMessage.success('删除成功')
        }
        }catch(e){
            console.log(e)
            ElMessage.error(e.message)
        }
      }).catch(()=>{})
}

const showFeedback = ref()
const showUpdataBox = ref(false)
//取消更新  
const onCancle = ()=>{
    showUpdataBox.value = false
}
//编辑反馈
const clickEdit = (feedback)=>{
   showUpdataBox.value = true
   showFeedback.value = feedback
}
   //图片列中删除已有的某个图片
const delImg = (id)=>{
    const imgsUrl = showFeedback.value.images
    imgsUrl.forEach((img,index)=>{
        if(img.id === id){
            imgsUrl.splice(index,1)
        }
    })
    showFeedback.value.images = imgsUrl
}


const imgFile = ref(FileList)
    //处理添加新图片
const onUpload = (imgFiles)=>{
    imgFile.value = imgFiles
}
    //处理移除新图片
const removeImg = (id)=>{
    imgFile.value.forEach((img,index)=>{
        if(img.uid === id){
            imgFile.value.splice(index,1)
        }
    })
}

//确认更新
const onUpdate = async ()=>{
    //构造请求数据
    const updateFeedbackData={
      id:showFeedback.value.id,
      content:showFeedback.value.content,
      contact_name:showFeedback.value.contactName,
      contact_phone:showFeedback.value.contactPhone,
      images:[],
      status:feedbackStatus.unprocessed
    }
    //处理旧图片
    const imageUrlArr = showFeedback.value.images
    imageUrlArr.forEach( (oldImg)=>{
        const img = {
            feedback_id:showFeedback.value.id,
            image_url:oldImg.image_url
        }
        updateFeedbackData.images.push(img)
    })
    //处理新上传的图片
    try{
        if(imgFile.value.length !== 0){
            const uploadPromises = imgFile.value.map((file) =>
            postFileApi(file).then((respUpImg) => ({
              feedback_id: showFeedback.value.id,
              image_url: respUpImg.data.data[0],
            }))
            );
            // 等待所有图片上传完成
            const newImages = await Promise.all(uploadPromises);
            newImages.forEach(img=>{
                updateFeedbackData.images.push(img)
            })
        }
    }catch(e){
        ElMessage.error('内部错误，请重试')
        console.log(e)
    }
    //发送更新请求
    try{
        console.log(updateFeedbackData)
        if(updateFeedbackData.content === ''){
            ElMessage.warning('请输入反馈内容')
            return
        }
        if(updateFeedbackData.contact_phone === ''){
            ElMessage.warning('请输入联系电话')
            return
        }
        if(updateFeedbackData.contact_name=== ''){
            ElMessage.warning('请输入联系人姓名')
            return
        }
        
        const resp = await updateFeedBackApi(updateFeedbackData)
        if(resp.data.code === 200){
            ElMessage.success('更新反馈成功')
            getFeedbackList(0,userInfo.id)
            showUpdataBox.value = false
            imgFile.value = []
        }
    }catch(e){
        console.log(e)
        ElMessage.warning('更新反馈异常，请联系管理员')
    }
   
}
//获取下一页数据
const getMore = async (pageInfo)=>{
    if(pageInfo.totalPages === 1 || pageInfo.number+1 >= pageInfo.totalPages){
        return
    }else{
        getFeedbackList(pageInfo.number+1,userInfo.id)
    } 
}
</script>
<template>
   <!-- 反馈更新弹出框 -->
   <el-dialog
        title="修改反馈信息"
        v-model="showUpdataBox">
        <el-form>
            <el-form-item prop="contactPhone">
                <span>联系人:</span>
                <el-input
                clearable
                placeholder="请输入联系人"
                v-model="showFeedback.contactName"
                ></el-input>
            </el-form-item>
            <el-form-item prop="contactPhone">
                <span>联系电话:</span>
                <el-input
                clearable
                placeholder="请输入电话号码"
                v-model="showFeedback.contactPhone"
                ></el-input>
            </el-form-item>
            <el-form-item prop="summary">
                 <span>反馈内容：</span>
                <el-input
                clearable
                v-model="showFeedback.content"
                type="textarea"
                ></el-input>
            </el-form-item>
            <div class="imgs" v-for="(img,index) in showFeedback.images" :key="index">
                <el-icon
                @click="delImg(img.id)"
                ><CloseBold /></el-icon>
                <img class="img" :src="img.image_url" alt="">
            </div>
            <upImg
            :showConfirm="true"
            @onUpload="onUpload"
            @onUpdate="onUpdate"
            @removeImg="removeImg"
            ></upImg>
            <el-form-item>
                 <el-button
                 @click="onCancle">
                    取消
                </el-button>
            </el-form-item>
        </el-form> 
    </el-dialog>
    <div class="feedback-box">
        <FeedbackList
        :feedbackList="showFeedbackList"
        :isFeedbacktUser="true"
        :showAudit="false"
        @onDel="clickDel"
        @queryList="getMore"
        @onEdit="clickEdit"
        >
        </FeedbackList>
    </div>
</template>

<style lang="scss" scoped>
.el-dialog{
    .el-form{
        .el-form-item{

        }
        .imgs{
            .img{
                width: 200px;
                height: 200px;
            }
        }
    }
}
.feedback-box{
    height: 80vh;
    overflow: scroll;
}
::-webkit-scrollbar{
    display: none;
    background-color: aliceblue;
}
</style>